﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using demo.Properties;
using zoyobar.shared.panzer.web.ib;
using Microsoft.VisualStudio.TextTemplating;
using System.CodeDom.Compiler;
using Skyline.WcfRest;

namespace demo
{
    public partial class Form1 : Form
    {
        IEBrowser ie;

        private string GetUrl(string path)
        {
            return Path.Combine(Settings.Default.WcfHost, path);
        }

        private Tuple<string, bool> ParseResponseType(string xml)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            var items = doc.DocumentElement.ChildNodes.Cast<XmlNode>().Select(n => n.Name);
            var distinct = items.Distinct();
            if (distinct.Count() != items.Count())
            {
                return Tuple.Create<string, bool>(distinct.First(), true);
            }
            else
            {
                return Tuple.Create<string, bool>(doc.DocumentElement.Name, false);
            }            
        }

        private Tuple<string, bool> ParseOperator(string url)
        {
            HttpWebRequest client = (HttpWebRequest)WebRequest.Create(GetUrl(url));

            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.Load(client.GetResponse().GetResponseStream());
            var node = doc.DocumentNode.SelectSingleNode("//div[@id='content']/p/pre[@class='response-xml']");
            if (node != null)
            {
                var xml = HtmlAgilityPack.HtmlEntity.DeEntitize(node.InnerHtml);
                return ParseResponseType(xml);
            }
            return null;
        }

        public Form1()
        {
            InitializeComponent();
            ie = new IEBrowser(this.wb);
        }

        private Uri GetScriptUri(string script)
        {
            return new Uri(Path.Combine(Application.StartupPath, "js", script));
        }

        private string GetScriptContent(string script)
        {
            return File.ReadAllText(Path.Combine(Application.StartupPath, "js", script));
            //return Uri.EscapeDataString(uri.AbsoluteUri);
        }

        private void InstallScript()
        {

        }

        private void btnInstallScript_Click(object sender, EventArgs e)
        {
            ie.InstallScript(GetScriptContent("wcfclient.js"));
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            wb.Navigate("about:blank");
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.AppStarting;
            try
            {
                wb.Navigate(Settings.Default.WcfHost);

                while (wb.ReadyState != WebBrowserReadyState.Complete)
                {
                    Application.DoEvents();
                }

                ie.InstallTrace();
                ie.InstallJQuery(GetScriptContent("jquery.js"));
                ie.InstallJQuery(GetScriptContent("json2.js"));
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private void btnHAP_Click(object sender, EventArgs e)
        {
            HttpWebRequest client = (HttpWebRequest)WebRequest.Create(GetUrl("help"));

            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.Load(client.GetResponse().GetResponseStream());
            doc.DocumentNode.SelectNodes("//div[@id='content']/table/tr")
                .Skip(1)
                .ForEach(tr => {
                    var td = tr.SelectNodes("td");
                    var url = td.First().InnerText;
                    var _operator = td.Skip(1).First().SelectSingleNode("a").GetAttributeValue("href", string.Empty);

                    var responseType = ParseOperator(_operator);
                    Console.WriteLine(string.Format("{0}/{1}/{2}", url, responseType.Item1, responseType.Item2));
                });
        }

        private void btnT4_Click(object sender, EventArgs e)
        {
            var host = new CustomT4Host();
            host.TemplateFileValue = "MyFirstScript.tt";
            host.Session = host.CreateSession();
            host.Session.Add("NameSpace", "demo");
            host.Session.Add("ClassName", "MyWcfApiClient");
            var WcfOperators = new List<WcfOperator>();
            WcfOperators.Add(new WcfOperator {
                Method = "GetHS300",
                Url = "market/hs300/{start}/{stop}",
                IsArray = true,
                ResponseType = "string",
                Args = new Dictionary<string, string>() { { "start", "datetime" }, { "stop", "datetime" } }
            });
            host.Session.Add("WcfOperators", WcfOperators);

            var content = File.ReadAllText("MyFirstScript.tt");

            Engine engine = new Engine();
            
            string language;
            string[] refs;

            engine.PreprocessTemplate(content, host, "demo", "demo", out language, out refs);
            
            var cs = engine.ProcessTemplate(content, host);
            Console.WriteLine(cs);

            foreach (CompilerError error in host.Errors)
            {
                Console.WriteLine(error.ToString());
            }
        }
    }
}
